import path from 'path';
import DBConnectTool from '../../../com/DBTool/DBConnectTool';
import compressible from '../../FSTool/compressible';
import zlibPromise from '../../FSTool/zlibPromise';

type FileInfo = {
    relativePath: string,
    buffer: Buffer,
    file_zip: string
}

// 保存文件列表到数据库，默认不压缩，大小不超过 250 mb
async function saveListToDB(DBName: string, fileInfo: FileInfo[]) {

    if (!fileInfo.length) {
        return true;
    }

    let fileInfoSqlSum = 'INSERT OR IGNORE INTO file_info  (file_name, file_path, file_zip, file_size, file_md5) VALUES ';

    let fileDataSqlSum = 'INSERT OR IGNORE INTO file_data (file_md5, file_data) VALUES ';

    for (let i = 0; i < fileInfo.length; i++) {
        const fileItem = fileInfo[i];

        if (!fileItem.buffer || !fileItem.relativePath) {
            continue;
        }

        let buffer = fileItem.buffer;
        let compressType = '';
        const relativePath = fileItem.relativePath;
        const md5 = require('crypto').createHash('md5').update(buffer).digest('hex');
        const size = buffer.length;
        const fileName = path.basename(fileItem.relativePath);

        let file_path = path.dirname(fileItem.relativePath);
        file_path = file_path === '\\' ? '\\' : file_path + '\\';
        file_path = file_path.replaceAll('/', '\\');

        if (buffer && compressible(relativePath) && !fileItem.file_zip) {
            buffer = await zlibPromise.zip(buffer);
            compressType = 'gzip';
        }

        fileInfoSqlSum += `('${fileName}', '${file_path}', '${compressType}', ${size}, '${md5}'),`;
        fileDataSqlSum += `('${md5}', X'${buffer.toString('hex')}'),`;
    }

    try {
        const dbTool = await DBConnectTool.openDB(DBName);

        await dbTool.sqlite3Promise.insertData(fileInfoSqlSum.substring(0, fileInfoSqlSum.length - 1), []);
        await dbTool.sqlite3Promise.insertData(fileDataSqlSum.substring(0, fileDataSqlSum.length - 1), []);

        return true;
    } catch (e) {
        console.log(e);
        return false;
    }
}


export default saveListToDB;
